package cn.kgc.commons.interceptor;


import cn.kgc.commons.util.UserContextHolder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>添加描述信息</p>
 *
 */
@ConditionalOnClass(ResponseBodyAdvice.class)
public class LoginUserNameInterceptor implements HandlerInterceptor {

    /**
     * 调用控制器方法处理请求之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获得用户名
        String username= request.getHeader(UserContextHolder.LOGIN_USER_NAME);
        String userId= request.getHeader(UserContextHolder.LOGIN_USER_ID);
        if(username!=null){
            //获得的用户的信息 保存到了UserContextHolder类中的ThreadLocal中
            UserContextHolder.getInstance().setUserNameAndUserId(username,userId);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }


    /**
     * 控制器中的方法执行完毕,页面的内容渲染完毕以后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder userContextHolder= UserContextHolder.getInstance();
        userContextHolder.clear(); //清除ThreadLocal中的数据
    }
}
